package com.korustar.autumnal.codemodel;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Outputs model to an {@link OutputStream}
 * 
 * @author amir
 *
 */
public class CodeModelSimpleOutputter {
	private static final String FILE_EXTENSION_JAVA = ".java";

	private static final Logger LOGGER = LoggerFactory.getLogger(CodeModelSimpleOutputter.class);
	
	private String folderName;
	
	public void outputToStream(CodeModelContainerModel model, OutputStream os) throws IOException {
		model.outputToStream(os);
	}
	
	public void go(CodeModelContainerModel model) throws IOException {
		
		OutputStream os;
		String filename= getFolderName()+"/"+folderizeClassName(model.getContainerClassName())+FILE_EXTENSION_JAVA;
		File f= new File(filename);
		if(!f.exists()) {
			if(!f.getParentFile().exists()) {
				LOGGER.debug("making parent folder(s)");
				f.getParentFile().mkdirs();
			}
		}
		LOGGER.info("Writing to {}", filename);
		os= new FileOutputStream(filename);
		model.outputToStream(os);
		LOGGER.info("Finished writing to {}", filename);
	}

	private String folderizeClassName(String containerClassName2) {
		return containerClassName2.replace(".", "/");
	}

	public void setFolderName(String folderName) {
		this.folderName = folderName;
	}

	public String getFolderName() {
		return this.folderName;
	}



}
